from django.db import models


# Create your models here.


# 机场
class Airport(models.Model):
    code = models.CharField(max_length=3)
    city = models.CharField(max_length=64)

    def __str__(self):
        # return f"{self.code}: {self.city}"
        return f"{self.city}({self.code})"


# 航班
class Flight(models.Model):
    # origin = models.CharField(max_length=64)
    # destination = models.CharField(max_length=64)
    # foreign key: 外键  ForeignKey
    # cascade: 级联  CASCADE
    origin = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="departures")
    destination = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="arrivals")
    duration = models.IntegerField()

    def __str__(self):
        return f"{self.id}:  from {self.origin} to {self.destination}"

    def is_valid_flight(self):
        # assert check False
        # return self.origin != self.destination or self.duration >= 0
        return self.origin != self.destination and self.duration >= 0


# 旅客
class Passenger(models.Model):
    first = models.CharField(max_length=64)
    last = models.CharField(max_length=64)
    # 一对多
    # blank=True 允许为空
    # 可以通过passengers 查询所有乘客
    flights = models.ManyToManyField(Flight, blank=True, related_name="passengers")

    def __str__(self):
        return f"{self.first} {self.last}"
